﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace QWManage.Utils
{
    public class Common
    {
        private Common() { }
        public static string FormatInt32(int value)
        {
            return Regex.Replace(value.ToString("N"), ".00$", "");
        }
        public static void MessageBoxInformation(string message)
        {
            MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void MessageBoxWarning(string message)
        {
            MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static void CacheToken(string token, bool isTokenA = true)
        {
            string fileName = isTokenA ? "TokenA.dll" : "TokenB.dll";
            string fn = Path.Combine(Application.StartupPath, fileName);
            string contents = token + "\t" + DateTime.Now.ToString();
            File.WriteAllText(fn, contents, Encoding.UTF8);
        }

        public static string GetCachedToken(bool isTokenA = true)
        {
            string fileName = isTokenA ? "TokenA.dll" : "TokenB.dll";
            string fn = Path.Combine(Application.StartupPath, fileName);
            if (!File.Exists(fn)) return string.Empty;
            string contents = File.ReadAllText(fn, Encoding.UTF8);
            string[] arr = Regex.Split(contents, "\t");
            if (arr.Length == 2)
            {
                string token = arr[0];
                DateTime dt;
                if (DateTime.TryParse(arr[1], out dt))
                {
                    TimeSpan timeSpan = DateTime.Now - dt;
                    if (timeSpan.TotalMinutes < 30)
                        return token;
                }
            }
            return string.Empty;
        }
    }
}
